package com.index.remoteclient

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.Toast
import com.example.index.IEventBusService
import com.example.index.User
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var binder: IEventBusService? = null

    var pendingCreateUser = false
    var pendingFetchUser = false

    var seviceConnection = object : ServiceConnection {

        override fun onServiceDisconnected(name: ComponentName?) {

            textView2.text = "service disconnected"
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            binder = IEventBusService.Stub.asInterface(service)
            textView2.text = "service connected"
            processPendingTask()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun bindRemoteService() {

        val intent = Intent("com.example.remoteservice")
        intent.setPackage("com.example.index")

        bindService(intent,seviceConnection , Context.BIND_AUTO_CREATE)
    }

    private fun processPendingTask() {
        if (pendingFetchUser) {
            fetchUser(textView2)
        }
        pendingFetchUser = false
    }

    /**
     * 创建新User ,提交到远程服务
     */
    fun createUser(view: View) {
        if (binder == null) {
            pendingCreateUser = true
            bindRemoteService()
        } else {
            val successful = binder?.addUser(User("jacky", "12345", 19))

            if (successful != false) {
                Toast.makeText(applicationContext, "add user success", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(applicationContext, "add user failed", Toast.LENGTH_SHORT).show()
            }

        }


    }


    /**
     * 跨进程抓取远程的User,并且显示
     */
    fun fetchUser(view: View) {
        if (binder == null) {
            pendingFetchUser = true
        } else {
            val users = binder?.postUser()
            textView2.text = users?.joinToString { "${it.userName} - ${it.userid} - ${it.age}\n" }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(seviceConnection)
    }
}
